//
//  TenderJpChooseVC.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2022/3/22.
//  Copyright © 2022 zwb. All rights reserved.
//

import UIKit
 
class ZyaTenderJpChooseVC: ZyaTenderBaseTableVC,UISearchBarDelegate {
    
    var page = 1
    
    var titleStr:ZTBInnerType = ZTBInnerType.zbListKHW
    var dataArray = [ZyaZtbContentModel]()
    var z_zb_id = "" // 出价记录使用
    
    var listType = TBandJPType.TB
    var btnflag = "1"
    
    var backClosure:((ZyaZtbContentModel)->())?

    var followTag = ""
    var helper = ZyaTenderHelper()
    private var searchBar:UISearchBar?
    
    
    init(listType:TBandJPType = .TB,titleStr:ZTBInnerType,z_zb_id:String = "",searchTitle:String = "",followTag:String = "0") {
        super.init(nibName: nil, bundle: nil)
        self.titleStr = titleStr
        self.listType = listType
        self.followTag = followTag
        self.z_zb_id = z_zb_id
        self.helper.filterPa!.searchTitle = searchTitle
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setSearchBar()
        helper.callTableRefreshClosure = {
            self.tableView.mj_header?.beginRefreshing()
            
        }
        
        tableView.estimatedRowHeight = 50
        tableView.rowHeight = UITableView.automaticDimension
        
        tableView.mj_header = KSRefreshHeader { [unowned self] in
            self.page = 1
            self.network()
        }
        tableView.mj_footer = KSRefreshFooter { [unowned self] in
            self.page += 1
            self.network()
        }
        tableView.mj_header?.beginRefreshing()
        
        tableView.register(ZyaTenderJPChooseCell.self, forCellReuseIdentifier: ZyaTenderJPChooseCell.identifier)
      
       
         
        
        tableView.tableFooterView = UIView()
        
        
    }
    @objc func doneClickss() {
        self.searchBar!.resignFirstResponder()
    }
    
    func setSearchBar () {
        searchBar = TenderSearchBar(frame:CGRect(x:0,y:0,width:KSGlobal.screenW * 0.65,height:40))
        let toolbar = UIToolbar()
        toolbar.barStyle = UIBarStyle.default
        toolbar.sizeToFit()
        let buttonflexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
        let buttonDone = UIBarButtonItem(title: "完成", style: UIBarButtonItem.Style.done, target: self, action: #selector(doneClickss))
        buttonDone.tintColor = UIColor.black
        toolbar.setItems([buttonflexible, buttonDone], animated: true)
        
        searchBar!.inputAccessoryView = toolbar
        
        searchBar!.layer.cornerRadius = 15
        searchBar!.layer.masksToBounds = true
        
        // 导航栏背景不同，需要改变搜索框背景色
        var searBColor:UIColor!
        if  titleStr == .zbInfo_ylOA ||
                titleStr == .zbInfo_wlOA ||
                titleStr == .zbInfo_drugOA ||
                titleStr == .jpInfo_oaOA ||
                titleStr == .zbInfo_followTagOA ||
                titleStr == .jpInfo_followTagOA ||
                 titleStr == .tbRecord_followTagOA ||
                titleStr == .chujiaRecordJP {
        searBColor = UIColor(kshex: "#f7f7f7")
      } else {
        searBColor = .white
      }

        
        if #available(iOS 13.0, *) {
            searchBar!.searchTextField.backgroundColor = searBColor
            searchBar!.searchTextField.layer.cornerRadius = 18
            searchBar!.searchTextField.layer.masksToBounds = true
        } else {
            // Fallback on earlier versions
            let searchField = searchBar!.value(forKey: "searchField") as! UITextField
            searchField.backgroundColor = searBColor
            searchField.layer.cornerRadius = 18
            searchField.layer.masksToBounds = true
            
        }
        
        
        searchBar!.text = self.helper.filterPa!.searchTitle
        searchBar!.placeholder = "搜索"
        searchBar!.delegate = self
        let searchView = UIView(frame:CGRect(x:0,y:0,width:KSGlobal.screenW * 0.65 ,height:40))
        searchView.addSubview(searchBar!)
        self.navigationItem.titleView = searchView
      
    }
   
    @objc func mapAction() {
        
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        self.helper.filterPa!.searchTitle = searchBar.text.unwrap
        self.tableView.mj_header?.beginRefreshing()
    }
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.dataArray.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 
            let one = self.dataArray[indexPath.row]
  
                guard let cell = tableView.dequeueReusableCell(withIdentifier: ZyaTenderJPChooseCell.identifier, for: indexPath) as? ZyaTenderJPChooseCell else {
                    fatalError("cell error")
                }
             
                cell.makeConstrainsts(self.listType)
              
                
                one.innerType = titleStr
                 cell.one = one
        cell.btn2Closure = { [one, unowned self] btn,btnTitle in
            if let clo = self.backClosure {
                clo(one)
            }
            self.navigationController?.popViewController(animated: true)
        }
                
                return cell
        
            
          
       
        
        
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
         
        
    }
    func network () {
 
        let api = API.tender(.queryMytenderJpJoinList(z_begin_dt: self.helper.filterPa!.startDate, z_end_dt: self.helper.filterPa!.endDate, z_city: self.helper.filterPa!.zCity, z_price_min: self.helper.filterPa!.minMoney, z_price_max: self.helper.filterPa!.maxMoney, page: "\(page)", size: "\(KSGlobal.pageSize)", z_title: self.helper.filterPa!.searchTitle,z_status: self.helper.filterPa!.zStatus))
 
        
        KSNetwork.shared.doRequest(api,showHud: false) { [weak self] (data:BaseResult<ZyaZtbContentModel>) in
            guard let `self` = self else { return }
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    if self.page == 1 {
                        self.dataArray.removeAll()
                    }
                    self.dataArray += infos
                    self.tableView.reloadData()
                    self.tableView.mj_header?.endRefreshing()
                    if infos.count < KSGlobal.pageSize{
                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    } else {
                        self.tableView.mj_footer?.endRefreshing()
                    }
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
    }
    
    
    deinit {
        print("tenderfirst 销毁")
    }
}
